import { useState } from 'react';
import { useSearchParams, useNavigate, Navigate } from 'react-router-dom';
import { useMutation } from '@tanstack/react-query';
import toast from 'react-hot-toast';
import Markdown from 'react-markdown';
import remarkGfm from 'remark-gfm';

import postApis from '../../apis/posts';
import { toastError } from '../../components/toast-error';
import OnlyIfAuthenticated from '../../components/biz/OnlyIfAuthenticated';
import OnlyIfMyPostCollectionExists from '../../components/biz/OnlyIfMyPostCollectionExists';
import useUuid from '../../components/hook/useUuid';
import Button from '../../components/ui/Button';
import Input from '../../components/ui/Input';
import { toCollectionId } from '../params/collection-id';
import TagSelect from '../../components/util/TagSelect';

export default function CreatePostPage() {
  const [searchParam] = useSearchParams();
  const result = toCollectionId(searchParam.get('collectionId'));
  if (result.ok) {
    return (
      <OnlyIfAuthenticated>
        {() => (
          <OnlyIfMyPostCollectionExists collectionId={result.result}>
            {(collection) => <Creator collection={collection} />}
          </OnlyIfMyPostCollectionExists>
        )}
      </OnlyIfAuthenticated>
    );
  } else {
    return <Navigate to="/me/post-collections" />;
  }
}

type CreatorProps = {
  collection: PostCollection;
};

function Creator({ collection }: CreatorProps) {
  const [title, setTitle] = useState('');
  const [content, setContent] = useState('');
  const [uuid] = useUuid();
  const [tags, setTags] = useState<SimpleTag[]>([]);

  const navigate = useNavigate();

  const mutation = useMutation({
    mutationFn: async () => {
      await postApis.createPost({
        title,
        content,
        collectionId: collection.id,
        type: 'MD',
        tagIds: tags.map((it) => it.id),
        dedupKey: uuid,
      });
    },
    onError: (error) => {
      toastError(error);
    },
    onSuccess: () => {
      navigate(`/me/post-collections/${collection.id}`);
      toast.success('创建成功');
    },
  });

  // TODO: csrf

  return (
    <div>
      <h1>
        创建文章 - {collection.id} - {uuid}
      </h1>
      <div className="flex gap-2 mb-2">
        <Input className="flex-1" type="text" value={title} onChange={(e) => setTitle(e.target.value)} />
        <Button onClick={() => mutation.mutate()}>保存</Button>
      </div>
      <div className="flex mb-2">
        <TagSelect domain={1} value={tags} onChange={setTags} />
      </div>
      <div className="flex gap-2" style={{ height: 'calc(100vh - 260px)' }}>
        <textarea
          className="flex-1 block p-2 rounded-md shadow-sm ring-1 ring-inset"
          rows={8}
          value={content}
          onChange={(e) => setContent(e.target.value)}
        />
        <Markdown
          remarkPlugins={[remarkGfm]}
          className="flex-1 px-4 py-2 overflow-auto rounded-md shadow-sm ring-1 ring-inset prose border"
        >
          {content}
        </Markdown>
      </div>
    </div>
  );
}
